package mx.com.mindbits.bandpay.asynctask;

import mx.com.mindbits.bandpay.R;
import mx.com.mindbits.bandpay.utils.ConstantsValues;
import mx.com.mindbits.emvcardreader.usbinterface.CardCommands;
import mx.com.mindbits.emvcardreader.vo.EMVdata;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;

public class CardDeviceTask extends AsyncTask<Void, Void, EMVdata>{
	
	private CardCommands readerDevice;
	
	private Context contexto;
	private EMVdata dataEMV;
	private ProgressDialog delayDialog;
	private Intent broadcastIntent = new Intent();
	
	
	public CardDeviceTask(CardCommands readerDevice, ProgressDialog dialog,
			String compraDetail, Context contexto){
		this.readerDevice = readerDevice;		
		this.contexto = contexto;				
		this.delayDialog = dialog;
		broadcastIntent.setAction(ConstantsValues.ACTION_USED);	
	}
	
	public EMVdata getDataEMV(){
		return dataEMV;
	}
	public void setDataEMV(EMVdata dataEMV){
		this.dataEMV = dataEMV;
	}

	@Override
	protected void onPreExecute(){
				
		if(readerDevice.getReader().isOpened()){
			Log.d(ConstantsValues.TAG_READER, "El dispositivo esta abierto"+readerDevice.getSlot());
		try{				
			readerDevice.powerUp();
			readerDevice.setProtocol();				
		}catch(Exception e){			
			Log.e(ConstantsValues.TAG_READER, "Ha ocurrido una excepcion al intentar inicializar el dispositivo: ["+e+"]");				
		}
		}
				
	}
	@Override
	protected EMVdata doInBackground(Void... arg0) {		
		Log.d(ConstantsValues.TAG_READER, "Extrayendo datos de la tarjeta...");		
		try{
			switch(readerDevice.getReader().getState(readerDevice.getSlot())){
			case ConstantsValues.CARD_ABSENT:								
				Log.d(ConstantsValues.TAG_READER, "No hay tarjeta.");																
				break;				
			default:
				if(!ConstantsValues.MOUNT_PURCHASE.isEmpty()){
					setDataEMV(readerDevice.getCard(ConstantsValues.MOUNT_PURCHASE));				
					readerDevice.closeDevice();						
				}				
				ConstantsValues.REQUEST_SENDED = false;
				break;
			}																					
		}catch(Exception exception){
			Log.e(ConstantsValues.TAG_READER,"Error al leer la tarjeta..."+exception);					
		}
		
		return dataEMV;		
	}
	
	@Override 
	protected void onPostExecute(EMVdata dataEMV){	
		if(dataEMV != null){
			if(dataEMV.getARQC() == null){
				broadcastIntent.putExtra(ConstantsValues.ACTION_ATTACHED, contexto.getString(R.string.label_statusbar_readBad));
			}else{
				broadcastIntent.putExtra(ConstantsValues.ACTION_ATTACHED, contexto.getString(R.string.label_statusbar_read));
			}	
		}else{
			broadcastIntent.putExtra(ConstantsValues.ACTION_ATTACHED, contexto.getString(R.string.label_statusbar_readBad));
		}					
		contexto.sendBroadcast(broadcastIntent);
		delayDialog.dismiss();								
   }
}
